import type Handsontable from 'handsontable'
import simpleHash from '@/utils/modules/simple-hash'
import useReportStore, { type ListItem } from '@/store/modules/reportStore'
import useValidate from './useValidate'
import { saveReportDataOfCompanyPrimaryElectricityDevice, updateReportDataOfCompanyPrimaryElectricityDevice } from '@/api/modules/dataReport'
import type { MaybeRefOrGetter } from 'vue'

export default function useSubmitForTab(hotInstance: MaybeRefOrGetter<Handsontable | undefined>) {
  const hash = ref<number>(0)
  const reportStore = useReportStore()
  async function submitForTab(params: any, resolve: (value: boolean) => void, reject: (value: boolean) => void) {
    const hot = toValue(hotInstance)
    if (!hot) {
      return reject(false)
    }
    // 校验表格数据类型
    const validate = useValidate(hot)
    return validate().then(() => {
      if (params.id) {
        updateReportDataOfCompanyPrimaryElectricityDevice(params).then(() => {
          resolve(true)
        })
      }
      else {
        saveReportDataOfCompanyPrimaryElectricityDevice(params).then(({ data }) => {
          resolve(true)
          const newRow = {
            ...reportStore.row,
            id: data.id,
          } as ListItem
          reportStore.setRow(newRow)
        })
      }
    }).catch(() => {
      reject(false)
    }).finally(() => {
      hot?.render()
    })
  }

  function generateHash() {
    const hot = toValue(hotInstance)
    const sourceData = hot?.getSourceData() ?? []
    hash.value = simpleHash(JSON.stringify(sourceData))
  }

  function checkHash() {
    const hot = toValue(hotInstance)
    const sourceData = hot?.getSourceData() ?? []
    return hash.value !== simpleHash(JSON.stringify(sourceData))
  }

  return { submitForTab, generateHash, checkHash }
}
